package org.yun.util;

import com.alibaba.nacos.common.utils.UuidUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;


/**
 * AES 是一种可逆加密算法，对用户的敏感信息加密处理 对原始数据进行AES加密后，在进行Base64编码转化；
 * @author liyunfeng31
 */
public class AesUtil {

    private static final String sKey = "smkldospdosldaaa";
    private static final String ivStr = "0392039203920300";


    public static String encrypt(String sSrc) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            byte[] raw = sKey.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encrypted);
        }catch (Exception e){
            return null;
        }
    }
 

    public static String decrypt(String sSrc){
        try {
            byte[] raw = sKey.getBytes(StandardCharsets.US_ASCII);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = Base64.getDecoder().decode(sSrc);
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original, StandardCharsets.UTF_8);
        } catch (Exception ex) {
            return null;
        }
    }


 
    public static void main(String[] args) throws Exception {


        // 需要加密的字串
        for (int i = 0; i <1000 ; i++) {
            String cSrc =UuidUtils.generateUuid()+"1242143535"+i;
            // 加密
            long lStart = System.currentTimeMillis();
            String enString = AesUtil.encrypt(cSrc);
            System.out.println("加密前长度"+cSrc.length()+ "    加密后的字串是：" + enString.length()+"       "+enString);
        }

    }
 
}